<script>
import { sendSmsCode, createOrder, reportConversion } from "@/api/telecom/sms";

export default {
  name: "Telecom",
  data() {
    return {
      phoneNumber: "",
      verificationCode: "",
      scrollInterval: null,
      showOneGif: true,
      showTwoGif: false,
      countdown: 60,
      isCountingDown: false,
      countdownTimer: null,
      extendData: null, // Store extendData returned from the SMS verification code interface
      isSubmitting: false, // Prevent duplicate submissions
      isSendingSms: false, // Prevent clicking send verification code twice at the same time
      isAgreed: false,
      showPolicy: false,
      showModal: false,
      modalMessage: "",
      autoCloseTimer: null
    };
  },
  methods: {
    async getVerificationCode() {
      if (!this.phoneNumber || this.phoneNumber.length !== 11) {
        this.showAlert("请输入正确的手机号码");
        return;
      }

      // Already in countdown, don't perform operation
      if (this.isCountingDown) return;

      // Already sending SMS, don't perform operation
      if (this.isSendingSms) return;

      try {
        this.isSendingSms = true; // Set sending status to true

        const response = await sendSmsCode(this.phoneNumber);
        if (response.code === 200) {
          // Save extendData for subsequent ordering
          this.extendData = response.data.extendData;
          // Start countdown
          this.startCountdown();
          this.showAlert("验证码已发送，请注意查收");
        } else {
          this.showAlert(response.msg || "发送验证码失败");
        }
      } catch (error) {
        if (error.message === "获取手机号归属地失败") {
          this.showAlert("获取手机号归属地信息失败，请稍后重试");
        } else if (error.message === "暂不支持该号码归属地的业务办理") {
          this.showAlert(
            "抱歉，暂不支持该号码归属地的业务办理，仅支持广州、佛山、东莞、惠州、江门、湛江地区"
          );
        } else if (error.message === "该号码非中国电信号码，暂不支持办理") {
          this.showAlert("抱歉，该业务仅支持中国电信用户办理");
        } else if (error.message === "网络连接失败，请检查您的网络连接并重试") {
          this.showAlert("网络连接失败，请检查您的网络连接并重试");
        } else if (error.message === "请求超时，请稍后重试") {
          this.showAlert("请求超时，请稍后重试");
        } else {
          this.showAlert("发送验证码失败，请稍后重试");
        }
        console.error("发送验证码出错:", error);
      } finally {
        this.isSendingSms = false; // Whether success or failure, set sending status to false
      }
    },
    
    // Start countdown
    startCountdown() {
      this.isCountingDown = true;
      this.countdown = 60;

      this.countdownTimer = setInterval(() => {
        this.countdown--;

        if (this.countdown <= 0) {
          // Countdown ends
          clearInterval(this.countdownTimer);
          this.isCountingDown = false;
        }
      }, 1000);
    },

    async handleSubmit() {
      if (!this.phoneNumber || !this.verificationCode) {
        this.showAlert("请填写完整信息");
        return;
      }

      if (this.isSubmitting) {
        return; // Prevent duplicate submissions
      }

      if (!this.isAgreed) {
        this.showAlert("请先阅读并同意隐私条款");
        return;
      }

      try {
        this.isSubmitting = true;

        // Show the third animation
        document.querySelector(".hand3").style.display = "block";

        // Call order interface
        const response = await createOrder(
          this.phoneNumber,
          this.verificationCode,
          this.extendData
        );

        if (response.code === 200) {
          // Order success
          this.showAlert("恭喜您，办理成功！");

          // Ensure conversion data is sent to ByteDance (don't wait for response)
          reportConversion();

          // If the interface returns a redirect URL, jump to that page
          if (
            response.data &&
            response.data.otherData &&
            response.data.otherData.url
          ) {
            window.location.href = response.data.otherData.url;
          }
        } else {
          // Order failed
          this.showAlert(response.message || "办理失败，请稍后重试");
        }
      } catch (error) {
        console.error("下单失败:", error);
        if (error.message === "该号码非中国电信号码，暂不支持办理") {
          this.showAlert("抱歉，该业务仅支持中国电信用户办理");
        } else if (error.message === "暂不支持该号码归属地的业务办理") {
          this.showAlert(
            "抱歉，暂不支持该号码归属地的业务办理，仅支持广州、佛山、东莞、惠州、江门、湛江地区"
          );
        } else if (error.message === "网络连接失败，请检查您的网络连接并重试") {
          this.showAlert("网络连接失败，请检查您的网络连接并重试");
        } else if (error.message === "请求超时，请稍后重试") {
          this.showAlert("请求超时，请稍后重试");
        } else {
          this.showAlert("办理失败，请稍后重试");
        }
      } finally {
        this.isSubmitting = false;
        // Hide the third animation
        document.querySelector(".hand3").style.display = "none";
      }
    },

    // Handle phone input box click event
    handlePhoneInputFocus() {
      this.showOneGif = false;
    },

    // Handle phone input event
    handlePhoneInputChange(e) {
      this.phoneNumber = e.target.value;
      // When the phone number length is 11 digits, display two.gif
      if (this.phoneNumber.length === 11) {
        this.showTwoGif = true;
      } else {
        this.showTwoGif = false;
      }
    },

    // Handle document click event, display one.gif when clicking on elements outside the input box
    handleDocumentClick(e) {
      // Get phone input element
      const phoneInput = document.getElementById("tellphone");

      // If the click is not on the input box and the phone number length is not 11 digits, display one.gif
      if (
        e.target !== phoneInput &&
        (!this.phoneNumber || this.phoneNumber.length !== 11)
      ) {
        this.showOneGif = true;
      }
    },

    // Marquee functionality
    startScroll() {
      const scrollBox = document.querySelector(".scroll_box");
      if (!scrollBox) return;

      let marginLeft = 0;
      const speed = 16; // Scroll speed, the larger the value, the slower the speed

      this.scrollInterval = setInterval(() => {
        marginLeft -= 1;
        scrollBox.style.marginLeft = marginLeft + "px";

        // Get the width of the first element (including right margin)
        const firstItem = scrollBox.querySelector(".scroll_item");
        if (!firstItem) return;

        const itemWidth =
          firstItem.offsetWidth + parseInt(getComputedStyle(firstItem).marginRight);

        // When the first element is completely scrolled out of view, move it to the end and reset marginLeft
        if (Math.abs(marginLeft) >= itemWidth) {
          scrollBox.appendChild(firstItem);
          marginLeft = 0;
          scrollBox.style.marginLeft = marginLeft + "px";
        }
      }, speed);
    },

    showPrivacyPolicy() {
      this.showPolicy = true;
    },

    closePrivacyPolicy() {
      this.showPolicy = false;
    },

    showAlert(message, duration = 2000) {
      // Clear previous timer (if any)
      if (this.autoCloseTimer) {
        clearTimeout(this.autoCloseTimer);
      }

      this.modalMessage = message;
      this.showModal = true;

      // Set auto-close timer
      this.autoCloseTimer = setTimeout(() => {
        this.showModal = false;
      }, duration);
    }
  },
  mounted() {
    // Ensure the DOM is fully loaded
    setTimeout(() => {
      this.startScroll();
    }, 100);

    // Add document click event listener
    document.addEventListener("click", this.handleDocumentClick);
  },
  beforeDestroy() {
    if (this.scrollInterval) {
      clearInterval(this.scrollInterval);
    }

    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }

    if (this.autoCloseTimer) {
      clearTimeout(this.autoCloseTimer);
    }

    // Remove document click event listener
    document.removeEventListener("click", this.handleDocumentClick);
  }
};
</script>

<template>
  <div>
    <div class="container">
      <!-- 添加viewport meta标签 -->
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
      
      <!-- Top banner -->
      <div>
        <img src="@/assets/images/telecom/banner.jpg" alt="banner" class="responsive-img" />
      </div>
      <!-- Form area -->
      <div class="form-container">
        <!-- Marquee -->
        <div class="scroll_tips">
          <div class="scroll_box flex flex-align-center">
            <span class="scroll_item">136****6140抢到了</span>
            <span class="scroll_item">152****7094抢到了</span>
            <span class="scroll_item">159****5549抢到了</span>
            <span class="scroll_item">188****1436抢到了</span>
            <span class="scroll_item">147****0084抢到了</span>
            <span class="scroll_item">187****5205抢到了</span>
            <span class="scroll_item">136****6140抢到了</span>
            <span class="scroll_item">135****0972抢到了</span>
          </div>
        </div>
        <div class="phone-box">
          <input
            type="tel"
            inputmode="numeric"
            placeholder="请输入您的手机号码"
            id="tellphone"
            v-model="phoneNumber"
            @focus="handlePhoneInputFocus"
            @input="handlePhoneInputChange"
            maxlength="11"
          />
          <img
            class="hand"
            src="@/assets/images/telecom/one.gif"
            alt=""
            :style="{ display: showOneGif ? 'block' : 'none' }"
          />
        </div>
        <div class="msg-box">
          <input
            type="tel"
            inputmode="numeric"
            placeholder="请输入短信验证码"
            id="msgCode"
            v-model="verificationCode"
            maxlength="6"
          />
          <div class="get-flow-code position-y50 flex flex-align-center">
            <span class="line" style="color: #ff7900">|</span>
            <p
              class="flex flex-align-center flex-pack-justify-center"
              id="getCode"
              @click="getVerificationCode"
              v-if="!isCountingDown && !isSendingSms"
            >
              获取验证码
            </p>
            <p
              class="flex flex-align-center flex-pack-justify-center countdown"
              v-else-if="isCountingDown"
            >
              {{ countdown }}S
            </p>
            <p
              class="flex flex-align-center flex-pack-justify-center sending"
              v-else
            >
              发送中...
            </p>
          </div>
          <img
            class="hand1"
            src="@/assets/images/telecom/two.gif"
            alt=""
            :style="{ display: showTwoGif ? 'block' : 'none' }"
          />
          <img
            class="hand2"
            src="@/assets/images/telecom/three.gif"
            alt=""
            style="display: none"
          />
        </div>
        <div id="toApply">
          <div id="toApply_button" class="button_wrap" @click="handleSubmit">
            <img
              class="button button_ani responsive-img"
              src="@/assets/images/telecom/btn.gif"
              alt="立即办理"
            />
          </div>
          <img
            src="@/assets/images/telecom/for.gif"
            class="hand3 position-x50"
            style="display: none"
          />
        </div>
        <!-- Privacy policy checkbox -->
        <div class="privacy-policy">
          <input type="checkbox" id="agree" v-model="isAgreed" />
          <label for="agree">
            我已阅读并同意
            <a href="#" @click.prevent="showPrivacyPolicy">《隐私条款》</a>
          </label>
        </div>

        <!-- Privacy policy popup -->
        <div v-if="showPolicy" class="modal">
          <div class="modal-content">
            <span class="close" @click="closePrivacyPolicy">&times;</span>
            <div class="protocol-title">《隐私条款》</div>
            <div class="protocol-content">
              <p>尊敬的客户：</p>
              <p>
                根据《中华人民共和国反恐怖主义法》、《全国人民代表大会常务委员会关于加强网络信息保护的决定》、《电信和互联网用户个人信息保护规定》（工业和信息化部令第24号）和《电话用户真实身份信息登记规定》（工业和信息化部令第25号）等国家法律法规的要求，客户在中国联合网络通信有限公司各类营业网点（含自有营业厅、手机营业厅、网上营业厅、授权合作代理商等）办理固定电话、移动电话（含无线上网卡）入网、过户以及需要出示客户证件的有关业务时，客户应配合出示有效证件原件并进行查验、登记，登记信息包括姓名、证件类型、号码及地址等。同时，为更好地提供服务，需要客户提供如联系人、联系电话、通信地址、电子邮箱等信息。客户本人持有效证件可通过自有营业厅查询和/或更正本人信息，或登录手机营业厅查询本人信息。
              </p>
              <p>
                如客户拒绝依法提供个人有效证件及真实信息，我公司有权不提供服务或终止服务。
              </p>
              <p>
                为向客户提供优质、个性化的服务，包括但不限于提供通信服务、保障通信服务安全、改善服务质量、推介个性化产品等，我公司将遵循合法、正当、必要的原则，按照法律法规规定和/或协议约定使用留存客户个人信息，并妥善保管，严格保密，依法保护客户个人信息，非因下列事由，不对外泄露客户个人信息：
              </p>
              <p>(a)事先获得客户的明确授权；</p>
              <p>(b)根据有关的法律法规要求；</p>
              <p>(c)按照相关司法机关和/或政府主管部门的要求；</p>
              <p>(d)为维护社会公众的利益所必需且适当；</p>
            </div>
          </div>
        </div>
      </div>
      <!-- Purchase instructions -->
      <div class="notice">
        <img src="@/assets/images/telecom/rule.jpg" alt="notice" class="responsive-img" />
      </div>

      <!-- Toast notification (moved inside the main container) -->
      <div v-if="showModal" class="toast-container">
        <div class="toast">
          <p>{{ modalMessage }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 移动端适配基础样式 */
* {
  -webkit-tap-highlight-color: transparent;
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  overscroll-behavior: none;
}

.responsive-img {
  max-width: 100%;
  height: auto;
  display: block;
}

.container {
  max-width: 450px;
  margin: 0 auto;
  min-height: 100vh;
  width: 100%;
  overflow-x: hidden;
}

/* Marquee styles */
.scroll_tips {
  width: 100%;
  height: 40px;
  overflow: hidden;
  position: absolute;
  top: -30px;
}

.scroll_box {
  white-space: nowrap;
  height: 100%;
  margin-left: 0;
  width: max-content;
}

.scroll_item {
  width: 7rem;
  height: 1.5rem;
  line-height: 1.5rem;
  text-align: center;
  display: inline-block;
  padding: 0 10px;
  background-color: rgba(0, 0, 0, 0.44);
  color: #fff;
  font-size: 0.75rem;
  border-radius: 20px;
  margin-right: 10px;
}

.form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-image: url("../../assets/images/telecom/bg-red.jpg");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-position: center;
  padding: 2.2rem 0 1.5rem;
  position: relative;
}

.phone-box {
  width: 85%;
  position: relative;
  margin: 0 auto;
}

.phone-box input {
  width: 100%;
  margin-bottom: 1.3rem;
  border-width: 1px;
  border-style: solid;
  border-color: #e6e6e6;
  height: 2.8rem;
  border-radius: 1.5rem !important;
  padding: 0 1rem;
  font-size: 1rem;
  border: 0;
  outline: 0;
  -webkit-appearance: none;
  -webkit-border-radius: 1.5rem;
  line-height: normal;
}

.phone-box input::placeholder {
  color: #a4a9b7;
}

.hand {
  display: block;
  width: 11rem;
  position: absolute;
  left: 1rem;
  top: -1.9rem;
  -webkit-animation: none;
  animation: none;
}

.msg-box {
  width: 85%;
  height: 2.8rem;
  margin-bottom: 1.3rem;
  position: relative;
  margin: 0 auto;
}

.msg-box input {
  width: 100%;
  font-size: 0.9rem;
  margin-bottom: 1.3rem;
  border-width: 1px;
  border-style: solid;
  border-color: #e6e6e6;
  height: 2.8rem;
  border-radius: 1.5rem !important;
  -webkit-border-radius: 1.5rem;
  padding: 0 1rem;
  outline: 0;
  -webkit-appearance: none;
  border: 0;
}

.msg-box input::placeholder {
  color: #a4a9b7;
}

.get-flow-code {
  display: flex;
  position: absolute;
  height: 2.7rem;
  right: 0 !important;
  border-radius: 0 1.5rem 1.5rem 0;
  top: 50%;
  transform: translateY(-50%);
  align-items: center;
}

.get-flow-code p {
  background: transparent;
  display: flex;
  align-items: center;
  color: #ff7900;
  height: 1.6rem;
  font-size: 0.85rem;
  width: 5rem;
  justify-content: center;
  cursor: pointer;
}

.countdown {
  color: #ff7900;
  font-size: 0.85rem;
  text-decoration: none;
  cursor: default;
}

.sending {
  color: #ff7900;
  font-size: 0.85rem;
  text-decoration: none;
  cursor: default;
}

.hand1 {
  position: absolute;
  width: 4rem;
  right: 0.5rem;
  top: -2rem;
}

.hand2 {
  position: absolute;
  width: 11rem;
  left: 0.5rem;
  top: -1.7rem;
}

@keyframes scaleDraw {
  0% {
    -webkit-transform: scale(1);
    transform: scale(1);
  }
  25% {
    -webkit-transform: scale(0.9);
    transform: scale(0.9);
  }
  50% {
    -webkit-transform: scale(1);
    transform: scale(1);
  }
  75% {
    -webkit-transform: scale(0.9);
    transform: scale(0.9);
  }
}

.button {
  width: 70%;
  max-width: 280px;
  margin: 0 auto;
  display: block;
}

#toApply {
  position: relative;
  text-align: center;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 10px 0;
}

#toApply_button {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

.button_wrap {
  animation: scaleDraw 2s infinite;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;
  display: flex;
  justify-content: center;
  width: 100%;
}

.hand3 {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.position-x50 {
  left: 50%;
  transform: translateX(-50%);
}

.position-y50 {
  top: 50%;
  transform: translateY(-50%);
}

.flex {
  display: flex;
}

.flex-align-center {
  align-items: center;
}

.flex-pack-justify-center {
  justify-content: center;
}

.privacy-policy {
  margin-top: 10px;
  font-size: 14px;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
}

.privacy-policy input[type="checkbox"] {
  width: 16px;
  height: 16px;
  margin-right: 5px;
}

.privacy-policy a {
  color: #ff7900;
  text-decoration: none;
}

.modal {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
}

.modal-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 90%;
  background-color: #fff;
  border-radius: 0.625rem;
  height: 60vh;
  max-height: 500px;
}

.close {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 24px;
  cursor: pointer;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
}

.protocol-title {
  font-size: 1.25rem;
  font-weight: 550;
  line-height: 1.25rem;
  padding: 0.625rem;
  text-align: center;
  margin-top: 10px;
}

.protocol-content {
  font-size: 0.9375rem;
  padding: 0 0.625rem 0.625rem;
  overflow-y: auto;
  height: calc(100% - 50px);
  width: 100%;
  -webkit-overflow-scrolling: touch;
}

.toast-container {
  position: fixed;
  top: 20px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  z-index: 999;
  pointer-events: none;
}

.toast {
  max-width: 280px;
  padding: 12px 20px;
  border-radius: 20px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  animation: toastFadeIn 0.3s, toastFadeOut 0.3s 1.7s;
  font-size: 14px;
}

@keyframes toastFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes toastFadeOut {
  from {
    opacity: 1;
    transform: translateY(0);
  }
  to {
    opacity: 0;
    transform: translateY(-20px);
  }
}

/* 修复iOS上的输入框问题 */
input[type="text"],
input[type="tel"],
input[type="number"],
textarea {
  -webkit-appearance: none;
  border-radius: 0;
}

/* 防止iOS缩放 */
@media screen and (max-width: 768px) {
  input[type="text"],
  input[type="tel"],
  input[type="number"],
  textarea {
    font-size: 16px;
  }
}

:root {
  font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
  line-height: 1.5;
  font-weight: 400;

  color-scheme: light dark;
  color: rgba(255, 255, 255, 0.87);
  background-color: #242424;

  font-synthesis: none;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

html {
  font-size: 20.75px;
}

a {
  font-weight: 500;
  color: #646cff;
  text-decoration: inherit;
}

a:hover {
  color: #535bf2;
}

body {
  margin: 0;
  display: flex;
  place-items: center;
  min-width: 320px;
  min-height: 100vh;
}

h1 {
  font-size: 3.2em;
  line-height: 1.1;
}

button {
  border-radius: 8px;
  border: 1px solid transparent;
  padding: 0.6em 1.2em;
  font-size: 1em;
  font-weight: 500;
  font-family: inherit;
  background-color: #1a1a1a;
  cursor: pointer;
  transition: border-color 0.25s;
}

button:hover {
  border-color: #646cff;
}

button:focus,
button:focus-visible {
  outline: 4px auto -webkit-focus-ring-color;
}

.card {
  padding: 2em;
}

#app {
  margin: 0 auto;
  /* text-align: center; */
}

img {
  width: 100%;
  vertical-align: middle;
}

@media (prefers-color-scheme: light) {
  :root {
    color: #213547;
    background-color: #ffffff;
  }

  a:hover {
    color: #747bff;
  }

  button {
    background-color: #f9f9f9;
  }
}
</style>
